<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row
        ><el-col
          ><el-button type="primary" @click="showAddDialog"
            >添加分类</el-button
          ></el-col
        ></el-row
      >

      <tree-table
        :data="cataList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        index-text="序号"
        show-index
        border
      >
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: green"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <template slot="isleve" slot-scope="scope">
          <el-tag type="primary" v-if="scope.row.cat_level === 0" size="mini"
            >一级</el-tag
          >
          <el-tag
            type="success"
            v-else-if="scope.row.cat_level === 1"
            size="mini"
            >二级</el-tag
          >
          <el-tag type="warning" v-else size="mini">三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <div>
            <el-tooltip
              effect="dark"
              content="编辑"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditCateDialog(scope.row.cat_id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="delByCateId(scope.row.cat_id)"
              ></el-button>
            </el-tooltip>
          </div>
        </template>
      </tree-table>
      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[10, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加商品分类 -->
    <el-dialog
      title="添加商品"
      :visible.sync="addDialogVisible"
      width="40%"
      @close="addDialogClose"
    >
      <!-- 主体内容部分 -->
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="18%"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" prop="cat_pid">
          <el-cascader
            v-model="selectKeys"
            :props="cascaderProps"
            :options="parentCateList"
            @change="handleChangeCate"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <!-- 底部按钮部分 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑商品分类 -->
    <el-dialog
      title="编辑商品分类"
      :visible.sync="editDailogVisible"
      width="40%"
      @close="editDialogClose"
    >
      <!-- 主体内容部分 -->
      <el-form
        :model="editCateForm"
        :rules="editCateFormRules"
        ref="editCateFormRef"
        label-width="18%"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮部分 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDailogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      queryInfo: { type: 3, pagenum: 1, pagesize: 10 },
      cataList: [],
      total: 0,
      columns: [
        {
          title: "分类名称",
          key: "cat_name",
        },
        {
          title: "是否有效",
          type: "template",
          template: "isok",
        },
        {
          title: "排序",
          type: "template",
          template: "isleve",
        },
        {
          title: "操作",
          type: "template",
          template: "opt",
          width: "130px",
        },
      ],
      addCateForm: {
        cat_pid: 0,
        cat_name: "",
        cat_level: 0,
      },
      addDialogVisible: false,
      addCateFormRules: {
        cat_name: [
          { required: true, message: "字段不能空！", trigger: "blur" },
          { min: 3, max: 10, message: "字符长度在3-10之间", trigger: "blur" },
        ],
      },
      parentCateList: [],
      careValue: "",
      cascaderProps: {
        expandTrigger: "hover",
        checkStrictly: true,
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      selectKeys: [],
      editDailogVisible: false,
      editCateForm: {},
      editCateFormRules: {
        cat_name: [
          {
            required: true,
            message: "分类名称不能为空!",
            trigger: "blur",
          },
          {
            min: 3,
            max: 15,
            message: "字符长度在3-10之间",
            trigger: "blur",
          },
        ],
      },
      editId: "",
    };
  },
  created() {
    this.getCategories();
  },
  methods: {
    async getCategories() {
      const { data: res } = await this.$http.get("/categories", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      //console.log(res.data);
      this.cataList = res.data.result;
      this.total = res.data.total;
    },
    handleSizeChange(newSize) {
      console.log(`每页 ${newSize} 条`);
      this.queryInfo.pagesize = newSize;
      this.getCategories();
    },
    handleCurrentChange(newPage) {
      console.log(`当前页: ${newPage}`);
      this.queryInfo.pagenum = newPage;
      this.getCategories();
    },
    showAddDialog() {
      this.getParentList();
      this.addDialogVisible = true;
    },
    addDialogClose() {
      this.$refs.addCateFormRef.resetFields();
      this.selectKeys = [];
      this.addCateForm.cat_level = 0;
      this.addCateForm.cat_pid = 0;
    },
    /* 获取父级数据 */
    async getParentList() {
      const { data: res } = await this.$http.get("/categories", {
        params: {
          type: 2,
        },
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取父级数据失败！");
      this.parentCateList = res.data;
      console.log(res.data);
    },
    handleChangeCate() {
      console.log(this.selectKeys[this.selectKeys.length - 1]);
      if (this.selectKeys.length > 0) {
        this.addCateForm.cat_pid = this.selectKeys[this.selectKeys.length - 1];
        this.addCateForm.cat_level = this.selectKeys.length;
        console.log(this.addCateForm.cat_level);
        return;
      } else {
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
      }
    },
    addCate() {
      console.log(this.addCateForm);
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "/categories",
          this.addCateForm
        );
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg);
        }
        this.$message.success("添加分类成功！");
        this.addDialogVisible = false;
        this.getCategories();
      });
    },
    //showEditCateDialog
    async showEditCateDialog(catId) {
      this.editDailogVisible = true;
      //根据ID查询
      const { data: res } = await this.$http.get("/categories/" + catId);
      if (res.meta.status !== 200) return this.$message.error("查询商品错误！");
      this.editCateForm = res.data;
      this.editId = res.data.cat_id;
    },
    /* 提交编辑分类名称 */
    saveEditCate() {
      this.$refs.editCateFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "/categories/" + this.editId,
          { cat_name: this.editCateForm.cat_name }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改商品分类错误！");
        }
        this.$message.success(res.meta.msg);
        this.editDailogVisible = false;
        this.getCategories();
      });
    },

    editDialogClose() {
      this.$refs.editCateFormRef.resetFields();
    },

    /* 根据ID删除分类 */
    async delByCateId(id) {
      console.log(id);
      const confirmStr = await this.$confirm(
        "你的这些数据将永久删除！",
        "提示",
        {
          confirmButtonText: "确定",
          canelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => error);
      console.log(confirm);
      if (confirmStr !== "confirm") {
        return this.$message.info("以取消删除！");
      }
      const { data: res } = await this.$http.delete("categories/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("删除分类失败！");
      }
      this.$message.success("删除成功！");
      this.getCategories();
    },
  },
  watch: {
    handlerValue() {
      if (this.$refs.refHandle) {
        this.$refs.refHandle.dropDownVisible = false; //监听值发生变化就关闭它
      }
    },
  },
  mounted() {
    //点击文本就让它自动点击前面的input就可以触发选择。但是因组件阻止了冒泡，暂时想不到好方法来触发。
    //这种比较耗性能，暂时想不到其他的，能实现效果了。
    setInterval(function () {
      document.querySelectorAll(".el-cascader-node__label").forEach((el) => {
        el.onclick = function () {
          if (this.previousElementSibling) this.previousElementSibling.click();
        };
      });
    }, 1000);
  },
};
</script>
<style lang="less" scoped>
.el-row {
  margin-bottom: 15px;
}
.el-cascader {
  width: 100%;
}
</style>
